import useDocumentTitle from '@/hooks/useDocumentTitle';

import { useEffect, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';

import { Header } from '@/components/Header/Header';
import { AuthLayout } from '@/components/AuthLayout';
import { TextField } from '@/components/Fields';
import { CustomButton } from '@/components/CustomButton'
import { useLogin } from '@/hooks/useLogin';
import { Footer } from '@/components/Footer';
import { useAuth } from '@hooks/AuthContext';

import { Spin, Alert } from 'antd';

export default function Login() {
  useDocumentTitle('登录-高考志愿填报系统');
  const { login, response, error, isOk, isLoading: isLogining } = useLogin();
  const [phone_number, setphone_number] = useState('');
  const [password, setPassword] = useState('');
  const navigate = useNavigate();
  const { isValidToken } = useAuth();

  useEffect(() => {
    if (!isLogining && response && isOk && response.detail) {
      const timer = setTimeout(() => {
        navigate('/');
      }, 1000);

      return () => {
        clearTimeout(timer);
      };
    }
  }, [isLogining, response, isOk, navigate]);

  const handleLogin = async (e) => {
    e.preventDefault();
    await login({ phone_number, password });
  };

  if (isValidToken) {
    navigate('/');
  } else {
    return (
      <Spin spinning={isLogining}>
        <Header />
        <AuthLayout
          title="Sign in to account"
          subtitle={
            <>
              Don’t have an account?{' '}
              <Link to="/register" className="text-sky-700 select-all">
                Sign up
              </Link>{' '}
              for a free trial.
            </>
          }
        >
          <form className='max-w-sm'>
            <div className="space-y-6">
              <TextField
                label="手机号"
                id="phone_number"
                name="phone_number"
                value={phone_number}
                autoComplete="tel"
                inputClass={`${!isLogining && response && !isOk && response.detail ? 'ring-2 ring-red-500' : ''}`}
                onChange={(e) => setphone_number(e.target.value)}
                required
              />
              <TextField
                label="密码"
                id="password"
                name="password"
                value={password}
                type="password"
                onChange={(e) => setPassword(e.target.value)}
                inputClass={`${!isLogining && response && !isOk && response.detail ? 'ring-2 ring-red-500' : ''}`}
                autoComplete="current-password"
                required
              />
              <CustomButton type="submit" className="inline-flex justify-center rounded-lg text-sm font-semibold py-2.5 px-4 bg-sky-700 text-white hover:bg-sky-600 w-full" onClick={handleLogin}>
                Sign in to account
              </CustomButton>
              {!isLogining && response && !isOk && response.detail && <Alert message={response.detail} type='error' className='mb-6 text-center text-red-600'></Alert>}
              {!isLogining && response && isOk && response.detail && <Alert message={response.detail} type='success' className='mb-6 text-center text-green'></Alert>}
            </div>
          </form>
        </AuthLayout>
        <Footer />
      </Spin>
    )
  }
}

